<?php

namespace app\controller\api\controller;

use app\enum\StatusConstant;
use app\popo\model\Setmeal;
use app\popo\model\SetmealDish;
use app\service\SetmealService;
use app\support\ResponseHelper;
use DI\Attribute\Inject;
use Shayvmo\WebmanAnnotations\Annotations\DeleteMapping;
use Shayvmo\WebmanAnnotations\Annotations\GetMapping;
use Shayvmo\WebmanAnnotations\Annotations\PostMapping;
use Shayvmo\WebmanAnnotations\Annotations\RestController;
use support\Db;
use Webman\Http\Request;

#[RestController("/api/setmeal")]
class SetmealController
{
    #[Inject]
    protected SetmealService $setmealService;

    #[GetMapping("/page")]
    public function listOf(Request $request)
    {
        $listContainer = $this->setmealService->listOf($request->all());
        return ResponseHelper::successJson($listContainer->toArray());
    }


    #[PostMapping]
    public function save(Request $request)
    {
        Db::beginTransaction();
        try {
            $this->setmealService->saveWithDishes($request->all());
            Db::commit();
            return ResponseHelper::successJson();
        } catch (\Throwable $throwable) {
            Db::rollBack();
            return ResponseHelper::failJson($throwable->getMessage());
        }

    }

    #[GetMapping("/{id}")]
    public function getItem($id)
    {
        $data = $this->setmealService->getById($id);
        return ResponseHelper::successJson($data);
    }

    #[DeleteMapping("/{ids}")]
    public function delete($ids)
    {
        Db::beginTransaction();
        try {
            $idArr = explode(",", $ids);
            foreach ($idArr as $id) {
                $setmeal = Setmeal::query()->find($id);
                if ($setmeal->status == StatusConstant::ENABLE) {
                    throw new \RuntimeException("套餐{$setmeal->name}正在售卖中，不能删除");
                }
                SetmealDish::query()->where("setmeal_id", $setmeal->id)->delete();
                $setmeal->delete();
            }
            Db::commit();
            return ResponseHelper::successJson();
        } catch (\Throwable $throwable) {
            Db::rollBack();
            return ResponseHelper::failJson($throwable->getMessage());
        }
    }


    #[PostMapping("/status/{status}")]
    public function startOrStop($status, Request $request)
    {
        $this->setmealService->startOrStop($status, $request->get("id"));
        return ResponseHelper::successJson();
    }
}